package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.entity.ApArticleConfig;
import com.heima.model.article.entity.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.constants.ArticleContants;
import com.heima.model.constants.KafkaMessageConstants;
import com.heima.model.search.vo.SearchArticleVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章基础信息表(ApArticle)表服务实现类
 *
 * @author makejava
 * @since 2023-06-15 21:21:03
 */
@Service("apArticleService")
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Resource
    private ApArticleMapper apArticleMapper;

    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    @Resource
    private ApArticleFreemarkerService apArticleFreemarkerService;

    @Resource
    private KafkaTemplate kafkaTemplate;
    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null || dto.getNewsId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //1. 文章库之前没有这个文章 --- 执行新增
        LambdaQueryWrapper<ApArticle> wrapper = Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getNewsId, dto.getNewsId());
        ApArticle article = apArticleMapper.selectOne(wrapper);
        if (article == null) {
            //1.1 新增文章基础信息
            //apArticle.setId(snowflakeIdWorker.nextId());
            apArticleMapper.insert(apArticle);

            //1.2 新增文章配置信息
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(1);
            apArticleConfig.setIsDelete(0);
            apArticleConfig.setEnable(1);
            apArticleConfig.setIsForward(1);

            apArticleConfigMapper.insert(apArticleConfig);

            //1.3 新增文章内容信息
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());

            apArticleContentMapper.insert(apArticleContent);
        } else {
            //2. 文章库之前有这个文章 --- 执行修改
            apArticle.setId(article.getId());

            //2.1 修改基础信息
            apArticleMapper.updateById(apArticle);

            //2.2 修改文章内容信息
            ApArticleContent apArticleContent = apArticleContentMapper.selectById(apArticle.getId());
            apArticleContent.setContent(dto.getContent());

            apArticleContentMapper.updateById(apArticleContent);
        }

        //生成静态HTML页面, 上传至MinIO
        String url = apArticleFreemarkerService.buildArticle2MinIo(apArticle.getId(), dto.getContent());

        //4. 修改文章表, 回填静态URL地址
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

        //发送消息给MQ---->同步文章数给ES
        if (StringUtils.isEmpty(url)){
            throw new RuntimeException("生成文章静态详情页失败");
        }

        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, searchArticleVo);
        searchArticleVo.setContent(dto.getContent());
        searchArticleVo.setStaticUrl(url);

        kafkaTemplate.send(KafkaMessageConstants.AP_ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));

        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public ResponseResult loadHomePage(ArticleHomeDto articleHomeDto) {
        //1.参数校验--为空设置默认值，超过50设置为50
        Integer size=articleHomeDto.getSize()==null|| articleHomeDto.getSize()<=0?10: articleHomeDto.getSize();
        size=Math.min(size,50);

        // 2. 频道校验
        String tag = articleHomeDto.getTag();
        tag = StringUtils.isEmpty(tag) ? ArticleContants.DEFAULT_TAG : tag;

        //3. 最小时间校验
        Date minTime = articleHomeDto.getMinBehotTime();
        minTime = minTime == null ? new Date() : minTime;

        //3. 最大时间校验
        Date maxTime = articleHomeDto.getMaxBehotTime();
        maxTime = maxTime == null ? new Date() : maxTime;

        //4. 封装查询参数
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("size", size);
        queryParam.put("tag", tag);
        queryParam.put("minTime", minTime);
        queryParam.put("maxTime", maxTime);
        queryParam.put("loadType", ArticleContants.LOAD_TYPE_NEW);

        List<ApArticle> apArticleList = apArticleMapper.queryArticleListByCondition(queryParam);


        //频道
        return ResponseResult.okResult(apArticleList);
    }
}

